package com.travelshare.business.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.travelshare.common.core.domain.TreeCommunity;
import com.travelshare.common.core.domain.entity.CommunityData;
import com.travelshare.common.utils.CommonUtils;
import com.travelshare.common.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.travelshare.business.mapper.InfoCommunityMapper;
import com.alibaba.fastjson2.JSON;
import com.travelshare.business.domain.InfoCommunity;
import com.travelshare.business.service.IInfoCommunityService;
import com.travelshare.business.utils.CustomCacheUtils;

/**
 * 社区信息Service业务层处理
 * 
 * @author travelshare
 * @date 2024-02-22
 */
@Service
@SuppressWarnings("rawtypes")
public class InfoCommunityServiceImpl implements IInfoCommunityService {
	@Autowired
	private InfoCommunityMapper infoCommunityMapper;

	/**
	 * 查询社区信息
	 * 
	 * @param communityId 社区信息主键
	 * @return 社区信息
	 */
	@Override
	public InfoCommunity selectInfoCommunityByCommunityId(Long communityId) {
		InfoCommunity cm = infoCommunityMapper.selectInfoCommunityByCommunityId(communityId);
		// InfoCommunity c = new InfoCommunity();
		// c.setCommunityId(communityId);
		// c.setClickNum(cm.getClickNum() + 1);
		// infoCommunityMapper.updateInfoCommunity(c);
		// getClickNumFromRedis(cm);
		// CustomCacheUtils.incrementCacheMapValue(ConstantsCustom.community_click_nums,
		// cm.getCacheId(), 1);
		return cm;
	}

	/*
	 * private void getClickNumFromRedis(InfoCommunity cm) {
	 * if(CustomCacheUtils.getCacheDataMapValue(ConstantsCustom.
	 * community_click_nums, cm.getCacheId()) != null) { cm.setClickNum((int)
	 * CustomCacheUtils.getCacheDataMapValue(ConstantsCustom.community_click_nums,
	 * cm.getCacheId())); } }
	 */

	/**
	 * 查询社区信息列表
	 * 
	 * @param infoCommunity 社区信息
	 * @return 社区信息
	 */
	@Override
	public List<InfoCommunity> selectInfoCommunityList(InfoCommunity infoCommunity) {
		return infoCommunityMapper.selectInfoCommunityList(infoCommunity);
	}

	/**
	 * 新增社区信息
	 * 
	 * @param infoCommunity 社区信息
	 * @return 结果
	 */
	@Override
	public int insertInfoCommunity(InfoCommunity infoCommunity) {
		InfoCommunity cm = infoCommunityMapper.selectInfoCommunityByCommunityId(infoCommunity.getParentId());
		infoCommunity.setCreateTime(DateUtils.getNowDate());
		Map<Character, Map> map = CustomCacheUtils.getSensitiveCache();
		String content = CommonUtils.matchingString(infoCommunity.getContent(), map);
		infoCommunity.setContent(content);
		String ancestors = infoCommunity.getParentId() + "";
		if (cm != null) {
			ancestors = cm.getAncestors() + "," + infoCommunity.getParentId();
		}
		infoCommunity.setAncestors(ancestors);
		return infoCommunityMapper.insertInfoCommunity(infoCommunity);
	}

	/**
	 * 修改社区信息
	 * 
	 * @param infoCommunity 社区信息
	 * @return 结果
	 */
	@Override
	public int updateInfoCommunity(InfoCommunity infoCommunity) {
		Map<Character, Map> map = CustomCacheUtils.getSensitiveCache();
		if (StringUtils.isNotBlank(infoCommunity.getContent())) {
			String content = CommonUtils.matchingString(infoCommunity.getContent(), map);
			infoCommunity.setContent(content);
		}
		infoCommunity.setUpdateTime(DateUtils.getNowDate());
		return infoCommunityMapper.updateInfoCommunity(infoCommunity);
	}

	/**
	 * 批量删除社区信息
	 * 
	 * @param communityIds 需要删除的社区信息主键
	 * @return 结果
	 */
	@Override
	public int deleteInfoCommunityByCommunityIds(Long[] communityIds) {
		return infoCommunityMapper.deleteInfoCommunityByCommunityIds(communityIds);
	}

	/**
	 * 删除社区信息信息
	 * 
	 * @param communityId 社区信息主键
	 * @return 结果
	 */
	@Override
	public int deleteInfoCommunityByCommunityId(Long communityId) {
		return infoCommunityMapper.deleteInfoCommunityByCommunityId(communityId);
	}

	@Override
	public int checkCommunityByCommunityIdsAndUserId(Long[] communityIds, Long userId) {
		return infoCommunityMapper.checkCommunityByCommunityIdsAndUserId(communityIds, userId);
	}

	@Override
	public int batchInfoCommunity(List<InfoCommunity> infoCommunityList) {
		return infoCommunityMapper.batchInfoCommunity(infoCommunityList);
	}

	/**
	 * app端 查询社区信息
	 * 
	 * @param communityId 社区信息主键
	 * @return 社区信息
	 */
	public InfoCommunity selectInfoCommunityForAppByCommunityId(Long communityId) {
		InfoCommunity cm = infoCommunityMapper.selectInfoCommunityByCommunityId(communityId);
		InfoCommunity c = new InfoCommunity();
		c.setCommunityId(communityId);
		c.setClickNum(cm.getClickNum() + 1);
		cm.setClickNum(c.getClickNum());
		infoCommunityMapper.updateInfoCommunity(c);
		return cm;
	}

	@Override
	public List<InfoCommunity> selectChildCommunityListById(Long communityId, Long userId) {
		return infoCommunityMapper.selectChildCommunityListById(communityId, userId);
	}

	@Override
	public List<TreeCommunity> selectCommunityTreeList(Long communityId, Long userId, String url ) {
		List<InfoCommunity> list = infoCommunityMapper.selectChildCommunityListById(communityId, userId);
		if(list != null && list.size() > 0) {
			for(InfoCommunity cm : list) {
        		if(StringUtils.isNotBlank(cm.getContent()) && cm.getContent().contains("/profile")) {
        			cm.setContent(cm.getContent().replaceAll("/profile" , url));
            	}
            	if(StringUtils.isNotBlank(cm.getPicPath()) && cm.getPicPath().contains("/profile")) {
            		cm.setPicPath(cm.getPicPath().replaceAll("/profile" , url));
            	}
            	if(StringUtils.isNotBlank(cm.getAvatar()) && cm.getAvatar().contains("/profile")) {
            		cm.setAvatar(cm.getAvatar().replaceAll("/profile" , url));
            	}
        	}
			String data = JSON.toJSONString(list);
			List<CommunityData> ls = JSON.parseArray(data, CommunityData.class);
			 return buildCommunityTreeSelect(ls);
		}
		return null;
	}

	private List<TreeCommunity> buildCommunityTreeSelect(List<CommunityData> list) {
		List<CommunityData> communityTrees = buildCommunityTree(list);
        return communityTrees.stream().map(TreeCommunity::new).collect(Collectors.toList());
	}

	private List<CommunityData> buildCommunityTree(List<CommunityData> communitys) {
		 List<CommunityData> returnList = new ArrayList<CommunityData>();
	        List<Long> tempList = communitys.stream().map(CommunityData::getCommunityId).collect(Collectors.toList());
	        for (CommunityData community : communitys)
	        {
	            // 如果是顶级节点, 遍历该父节点的所有子节点
	            if (!tempList.contains(community.getParentId()))
	            {
	                recursionFn(communitys, community);
	                returnList.add(community);
	            }
	        }
	        if (returnList.isEmpty())
	        {
	            returnList = communitys;
	        }
	        return returnList;
	}

	private void recursionFn(List<CommunityData> list, CommunityData t) {
		// 得到子节点列表
        List<CommunityData> childList = getChildList(list, t);
        t.setChildren(childList);
        for (CommunityData tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
	}

	private boolean hasChild(List<CommunityData> list, CommunityData tChild) {
		return getChildList(list, tChild).size() > 0;
	}

	private List<CommunityData> getChildList(List<CommunityData> list, CommunityData t) {
		List<CommunityData> tlist = new ArrayList<CommunityData>();
        Iterator<CommunityData> it = list.iterator();
        while (it.hasNext())
        {
        	CommunityData n = (CommunityData) it.next();
            if (n.getParentId() != null && n.getParentId().longValue() == t.getCommunityId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
	}
}
